init('mongo');
(function(){
	namespace('org.jsmud.db');
	
	org.jsmud.db.Mongo = function(host, port){
		this.host = host;
		this.port = port;
	}
	org.jsmud.db.Mongo.prototype = {
		getDb : function(dbName){
			return new org.jsmud.db.Mongo.DB({parent:this, dbname:dbName})
		}
	}
	org.jsmud.db.Mongo.DB = function(args){
		this.parent = args.parent;
		this.dbname = args.dbname;
		this.username = args.username;
		this.password = args.password;
	}
	org.jsmud.db.Mongo.DB.prototype = {
		buildQuery : function(criteria){
			var baseUrl = this.getBaseUrl();
			var query = '';
            var url = baseUrl + '/_find';
            if( criteria && criteria.example ){
                query = "?criteria=" + encodeURI(this._stringify(criteria.example));
            }
            if( criteria.limit ) query += (query?'&':'?')+'batch_size='+criteria.limit;
            
            url += query;
            console.log("url: " + url);
            return url;
        },
        getBaseUrl : function(){
            return "http://localhost:8080/db/test/" + this.dbname
        },
        findById : function(id, onResponse, onError){
        	var _id = {_id : id};
        	var q = {example:_id};
        	this.find(q, onResponse, onError);
        },
		find : function(query, onResponse, onError){
			console.log(query);
            this._ajax({
            	method : 'GET'
            	,url   : this.buildQuery(query)
            	,onSuccess   : onResponse
            	,onError     : onError
            });
		},
        save : function(obj, onResponse, onError){
        	if(obj._id){
        		this.update({_id:obj._id}, obj, onResponse, onError);
        	}else{
	            var s1 = this._stringify(obj)
	            console.log("URL : " + this.getBaseUrl() + "/_insert");
	            console.log("BODY: docs=[" + s1 + "]");
	            this._ajax({
	            	method : 'POST'
	            	,url   : this.getBaseUrl() + "/_insert"
	            	,contentType : 'application/x-www-form-urlencoded'
	            	,onSuccess   : onResponse
	            	,onError     : onError
	            	,body        : "docs=[" + s1 + "]"
	            });
        	}
        },
        update : function(criteria, value, onResponse, onError){
            var s1 = this._stringify(value);
            var c1 = this._stringify(criteria);
            console.log("URL : " + this.getBaseUrl() + "/_update");
            console.log("BODY: " + s1);
            this._ajax({
            	method : 'POST'
            	,url   : this.getBaseUrl() + "/_update"
            	,contentType : 'application/x-www-form-urlencoded'
            	,onSuccess   : onResponse
            	,onError     : onError
            	,body        : 'criteria='+c1+';newobj='+s1
            });
        },
        _stringify : function(obj){
        	try{
        		return JSON.stringify(obj);
        	}catch(e){
        		throw e;
        	}
        },
        
	}
})();